import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';

import {
    queryGetImpower,
    queryCallbackImpower,
    queryTencentDetail,
    queryBindCabinetCount
} from './service';

export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
    namespace: string;
    state: {};
    effects: {
        fetchImpower: Effect;
        fetchCallback: Effect;
        fetchDetail: Effect;
        fetchCabinetCount: Effect;
    };
    reducers: {
        save: Reducer;
    };
}

const Model: ModelType = {
    namespace: 'tencentImpower',

    state: {
        cabinetCount: 0,
        oldShelfCount: 0,
        newShelfCount: 0,
        dataInfo: {
            id: '',
        },
    },

    effects: {
        *fetchImpower({ payload }, { call, put }) {
            const response = yield call(queryGetImpower, payload);
            return fetchValidation(response);
        },

        *fetchCallback({ payload }, { call, put }) {
            const response = yield call(queryCallbackImpower, payload);
            return fetchValidation(response);
        },

        *fetchDetail({ payload }, { call, put }) {
            const response = yield call(queryTencentDetail, payload);
            const data = fetchValidation(response);

            yield data &&
                put({
                    type: 'save',
                    payload: {
                        dataInfo: Array.isArray(data.body) ? { id: false } : data.body,
                    },
                });
        },

        *fetchCabinetCount({ payload }, { call, put }) {
            const response = yield call(queryBindCabinetCount, payload);
            const data = fetchValidation(response);
            console.log(payload);
            const count = payload.type === 1 ? { cabinetCount: data.body } : payload.type === 2 ? { oldShelfCount: data.body } : { newShelfCount: data.body };

            yield data &&
                put({
                    type: 'save',
                    payload: count,
                });
        },
    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload,
            };
        },
    },
};

export default Model;
